# -*- coding: utf-8 -*-
import logging
import re
import time
from collections import defaultdict

BRANDS_RE    = re.compile(ur'<h2>.*?<span\s*class="en">(.*?)</span>.*?<span\s*class="th">(.*?)</span>')
BRANCHES_RE  = re.compile(ur'<div class="branch_header">.*?<span class="en">(.*?)</span>.*?<span class="th">(.*?)</span>')
#THEATRES_RE  = re.compile(ur'\<span class="theatre_name">(.*?)</span>')
THEATRES_RE  = re.compile(ur'<div\s*class="(theatretitle)">')
TELEPHONES_RE= re.compile(ur'Direct Line:([ \d-]+)')
MOVIES_RE    = re.compile(ur'class="movie_name">\s*<span class="en">(.*?)</span>\s*<span class="th">(.*?)</span>\s*<span class="lang">&nbsp;(.*?)</span>')
#SHOWTIMES_RE = re.compile(ur'<a\s*href=[\'\"]quickbook.*?>(.*?)</a>')
SHOWTIMES_RE = re.compile(ur'<span>(?:<a[^>]+>)?(\d+:\d+)(?:</a>)?</span>')

HTML_HEADER = '''
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en" dir="ltr"> 
<head> 
<title>Meang Eai Cineplex</title> 
<meta http-equiv="content-type" content="text/html; charset=utf-8" /> 
<meta http-equiv="Content-Language" content="th" /> 
<meta name="language" content="th" /> 
<meta name="robots" content="index, follow" /> 
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />

<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
  <script>
  $(document).ready(function() {
    $("#main").accordion({ 
        autoHeight: false, 
        fillSpace : false, 
        collapsible: true,
        active: false,
        navigation: true
    });
  });
  </script>
</head>
<body>
'''

HTML_FOOTER = '''
Brought to you by: <a href="http://lewcpe.com/blog/archives/1049/">LewCPE</a>
</body>
</html>
''' 

def assignpos(lista,lastpos):
    tmp = [(v.end(),v.groups()) for v in lista]
    ret = [((v[0],w[0]),v[1]) for v,w in zip(tmp[:-1],tmp[1:])]
    ret.append(((tmp[-1][0],lastpos),tmp[-1][1]))
    return ret
    
def assignchild(lista,listb):
    rel = []
    for itema in lista:
        children = [itemb[1] for itemb in listb if itemb[0][0] > itema[0][0] and itemb[0][0] < itema[0][1]]
        rel.append((itema[0],(itema[1],children)))
    return rel

def process_cineplex(s):
    s = ''.join(s)
    s = s.decode('cp874')
    s = s.replace('\n','')
    s = s.replace('\t','')
    lastpos = len(s)
    #brands     = assignpos(BRANDS_RE.finditer(s),lastpos)
    branches   = assignpos(BRANCHES_RE.finditer(s),lastpos)
    theatres   = assignpos(THEATRES_RE.finditer(s),lastpos)
    telephones = assignpos(TELEPHONES_RE.finditer(s),lastpos)
    movies     = assignpos(MOVIES_RE.finditer(s),lastpos)
    showtimes  = assignpos(SHOWTIMES_RE.finditer(s),lastpos)
    logging.debug(showtimes)
    tmp = assignchild(movies,showtimes)
    tmp = assignchild(theatres,tmp)
    tmp = assignchild(telephones,tmp)
    tmp = assignchild(branches,tmp)
    #tmp = assignchild(brands,tmp)
    if theatres:
        ret = [v[1] for v in tmp]
    else:
        ret = []
    return ret
    
def print_cineplex(l,prefix=''):
    for v in l:
        print prefix+repr(v[0])
        if len(v) == 2:
            print_cineplex(v[1],prefix+'  ')
            
def format_cineplex(l):
    #out = '<h1>Last fetched:'+time.strftime('%d-%m-%Y %H:%M',time.localtime(time.time()+25200))+'</h1>\n'
    #out += '<div id="main">\n'
    out = ''
    for branch,tels in l:
        for tel,theatres in tels:
            #out += '    <h3><a href="#">'+branch[0]+' | '+branch[1]+' | '+tel[0].strip()+'</a></h3>\n'
            info = {
                'bcode':branch[0].replace(' ','_').lower(),
                'bname':branch[0],
                'bnameth':branch[1],
                'tel': tel[0]
                }
            out += '    <h3 id="%(bcode)s"><a href="#%(bcode)s">%(bname)s | %(bnameth)s | %(tel)s</a></h3>\n' % info
            out += '    <ul>\n'
            for i,(theatremark,movies) in enumerate(theatres):
                for movie,showtimes in movies:
                    out += '        <li>'+str(i+1)+' : '+' | '.join(movie)+' | '+' | '.join([show[0] for show in showtimes])+'</li>\n'
            out += '    </ul>\n'
    #out += '</div>\n'
    return out #HTML_HEADER + out + HTML_FOOTER
    
def format_error():
    return HTML_HEADER + '<h2>Data not ready</h2>' + HTML_FOOTER
    
SF_BRANCHES_RE  = re.compile(ur'<font\s+color=[\'"]#ffffff[\'"]\s*>\s*<b>(.*?)</b>')
SF_MOVIES_RE    = re.compile(ur'<font\s*color=["\']#ffffff["\']\s*>([\w\s\-]*?)\s*\(([\w\.\/]*?)\)</font>')
SF_SHOWTIMES_RE = re.compile(ur'Cinema\s*(\d+)\s+(\d+:\d+)')
SF_TEL_LIST = [("SFX COLISEUM PHUKET","076-209-042"),
                ("SFC JUNGCEYLON PHUKET","076-600-55"),
                ("SFC PATTAYA","033-003-557"),
                ("SFX PATTAYA BEACH","033-003-557"),
                ("SFC CHONBURI","033-003-222"),
                ("SFC HARBOR MALL","038-400-666"),
                ("SFC KHONKAEN","043-001-888")
                ]
SF_TEL_DICT = defaultdict(lambda : "02-268-8888")
SF_TEL_DICT.update(SF_TEL_LIST)
    
def format_sf(s):
    out = ''
    s = ''.join(s)
    s = s.replace('\n','')
    s = s.replace('\r','')
    s = s.replace('\t','')
    lastpos   = len(s)
    try:
        branch    = SF_BRANCHES_RE.findall(s)[0]
    except:
        branch = 'XXX'
    movies    = assignpos(SF_MOVIES_RE.finditer(s),lastpos)
    showtimes = assignpos(SF_SHOWTIMES_RE.finditer(s),lastpos)
    rels = assignchild(movies,showtimes)
    info = {
        'bcode' : branch.replace(' ','_').lower(),
        'bname' : branch,
        'tel'   : SF_TEL_DICT[branch]
        }
    out += '<h3 id="%(bcode)s"><a href="#%(bcode)s">%(bname)s | %(tel)s</a></h3>\n' % info
    out += '<ul>\n'
    dd = defaultdict(lambda : defaultdict(list)) 
    for pos,(movie,showtimes) in rels:
        for k,v in showtimes: 
            dd[k][movie].append(v)
    
    for theatre,v in sorted(dd.items(),lambda x,y: int(x[0])-int(y[0])):
        for (moviename,lang),showtime in v.items():
            out += '  <li>'+theatre+' : '+moviename+' ('+lang+') '+' | '.join(showtime)+'</li>\n'
    out += '</ul>\n'
    return out
    
CENTURY_THEATRES_RE = re.compile(ur'Table_showtime_cinema')
CENTURY_MOVIES_RE   = re.compile(ur'<a\s*href.*?showtime_link">(.*?)(\[\w+\])?</a>.*?showtime_time">(.*?)</td>')
    
def format_century(content):
    out = ''
    s = ''.join(content)
    s = s.replace('\n','')
    s = s.replace('\r','')
    s = s.replace('\t','')
    s = s.decode('cp874')
    lastpos = len(s)
    theatres = assignpos(CENTURY_THEATRES_RE.finditer(s),lastpos)
    movies   = assignpos(CENTURY_MOVIES_RE.finditer(s),lastpos)
    rels = assignchild(theatres,movies)
    out += '<h3 id="century"><a href="#century">Century | 02-247-9940</a></h3>\n'
    out += '<ul>\n'
    for i,(pos,(theatre,movies)) in enumerate(rels):
        for name,lang,showtime in movies:
            name = name.strip().replace(':','|')
            lang = '(EN)' if lang == '[Eng]' else '(TH)'
            showtime = ' | '.join(showtime.split(' &nbsp; '))
            out += '  <li>%d : %s | %s | %s </li>\n' % (i+1,name,lang,showtime)
            #print repr(movie)
    out += '</ul>\n'
    return out
    
APEX_THEATRES_RE = re.compile(ur'big_text">(.*?)</span>.*?Tel\.\s*([\d\-]*)')
APEX_SHOWTIMES_RE = re.compile(ur'style4">\s*<b>(.*?)</b>.*?style4">([\(\)\d\.\s\,]+)</span>')
    
def format_apex(content):
    out = ''
    s = ''.join(content)
    s = s.replace('\n','')
    s = s.replace('\r','')
    s = s.replace('\t','')
    lastpos = len(s)
    theatres = assignpos(APEX_THEATRES_RE.finditer(s),lastpos)
    movies   = assignpos(APEX_SHOWTIMES_RE.finditer(s),lastpos)
    rels = assignchild(theatres,movies)
    out += '<h3 id="apex"><a href="#apex">APEX (LIDO/SCALA/SIAM)</a></h3>\n'
    out += '<ul>\n'
    for pos,((theatre_name,tel),(movies)) in rels:
        for moviename, showtimes in movies:
            showtimes = showtimes.replace('(','')
            showtimes = showtimes.replace(')','')
            showtimes = showtimes.replace('.',':')
            showtimes = showtimes.split(' ')
            showtimes = ' | '.join(showtimes)
            out += '  <li>%s : %s | %s | %s</li>\n' %(theatre_name,moviename,showtimes,tel)
    out += '</ul>\n'
    return out
    
VISTA_THEATRES_RE = re.compile(ur'โรงที่\s*(\d+)')
VISTA_SHOWTIMES_RE   = re.compile(ur'<br \/>([^>]*?)<br \/>\s*(\([ENTH\-\/]+\))\s*<br \/>\s*([\d\:\s]+)<br \/>')
    
def format_vista(content):
    out = ''
    s = ''.join(content)
    s = s.replace('\n','')
    s = s.replace('\r','')
    s = s.replace('\t','')
    s = s.decode('utf-8')
    s = re.sub(ur'&#(\d+);',lambda x: unichr(int(x.group(1))), s)
    lastpos = len(s)
    theatres = assignpos(VISTA_THEATRES_RE.finditer(s),lastpos)
    movies   = assignpos(VISTA_SHOWTIMES_RE.finditer(s),lastpos)
    rels = assignchild(theatres,movies)
    out += '<h3 id="vista"><a href="#vista">VISTA Chiangmai | 053-894-415</a></h3>\n'
    out += '<ul>\n'
    for pos,((theatre_name,),(movies)) in rels:
        for moviename, lang, showtimes in movies:
            showtimes = showtimes.split(' ')
            showtimes = ' | '.join(showtimes)
            out += '  <li>%s : %s | %s | %s </li>\n' %(theatre_name,moviename,lang,showtimes)
    out += '</ul>\n'
    return out
    
DIANA_MOVIES_RE = re.compile(ur'CCCCCC">.*?\s*<font[^>]*color="#0099FF"[^>]*>(<[^>]*>)?([^<>]*?)(</[^>]*>)?</font>.*?'*2)
DIANA_LANG_RE   = re.compile(ur'(THAI|ENG)')
DIANA_SHOWTIMES_RE = re.compile(ur'<font color="#FFFF00"[^>]*>(\d)</font></strong></div></td>\s*<td[^>]*>(<div[^>]*>)?\s*(<p>)?<font[^>]*><strong>([\d\s\:]+)</strong>')

def format_diana(content):
    def repl_space(m):
        return ' '
    out = ''
    s = ''.join(content)
    s = s.decode('cp874')
    s = s.replace('\n','')
    s = s.replace('\t','')
    s = s.replace('\r','')
    s = s.replace('&nbsp;','')
    lastpos = len(s)
    movies    = assignpos(DIANA_MOVIES_RE.finditer(s),lastpos)
    langs     = assignpos(DIANA_LANG_RE.finditer(s),lastpos)
    showtimes = assignpos(DIANA_SHOWTIMES_RE.finditer(s),lastpos)
    dd = defaultdict(dict)
    tmp = assignchild(langs,showtimes)
    tmp = assignchild(movies,tmp)
    for pos,((no,movieth,no,no,movieen,no),langs) in tmp:
        movieth = ' '.join([w for w in movieth.strip().split(' ') if w])
        movieen = ' '.join([w for w in movieen.strip().split(' ') if w])
        if movieth != '-' and movieen != '-':
            moviename = movieth + ' | ' + movieen
        else:
            moviename = movieen if movieen != '-' else movieth
        langs = [(l,v) for l,v in langs if v] 
        for (lang,), listshowtime in langs:
            for theatre,no,no,showtimes in listshowtime:
                showtimes = ' | '.join([s for s in showtimes.split(' ') if s])
                tmpname = moviename+' | ('+lang+')'
                dd[theatre][tmpname] = showtimes
    out += '<h3 id="diana"><a href="#diana">DIANA (Hat-Yai) | 074-428-376</a></h3>\n'
    out += '<ul>\n'
    for theatre, v in sorted(dd.items()):
        for movie,showtimes in v.items():
            out += '  <li>%s : %s | %s</li>\n' %(theatre,movie,showtimes)
    out += '</ul>\n'
    return out
    
def test():
    temps = 'akwwbjzzzclxxx'
    lista = assignpos(re.finditer(ur'([abc])',temps),len(temps))
    listb = assignpos(re.finditer(ur'([ijkl])',temps),len(temps))
    listc = assignpos(re.finditer(ur'([wxyz])',temps),len(temps))
    print lista
    print listb
    listbc= assignchild(listb,listc)
    print "BC",listbc
    listz = assignchild(lista,listbc)
    
def test_cineplex():
    f = open('./test/cineplex.html')
    s = process_cineplex(f.readlines())
    print format_cineplex(s).encode('utf-8')
    
def test_sf():
    f = open('./test/sfx.html')
    print format_sf(f.readlines())
    
def test_century():
    f = open('./test/century.html')
    print format_century(f.readlines())
    
def test_apex():
    f = open('./test/apex.html')
    print format_apex(f.readlines())
    
def test_vista():
    f=open('./test/vista.html')
    print format_vista(f.readlines())
    
def test_diana():
    f=open('./test/diana.html')
    print format_diana(f.readlines())
    
if __name__=="__main__":
    test_sf()
    test_cineplex()
    test_apex()
    test_century()
    test_vista()
    test_diana()
